package com.next.aap.server.tasks;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.next.aap.messages.NewFacebookNotificationMessage;
import com.next.aap.messages.NotificationMessage;
import com.next.aap.server.cache.FacebookCache;
import com.next.aap.server.services.AppService;

@Component
public class FacebookFeederTask {

	@Autowired
	private AppService appService;
	@Autowired
	private TaskManager taskManager;
	@Autowired
	private FacebookCache facebookCache;

	

	private final String facebookPageUrl = "https://graph.facebook.com/290805814352519/posts?limit=15&fields=link,actions,id,name,picture,message,type,status_type&date_format=d-M-Y%20h:i%20e&access_token=CAACjs4PJeR8BADXw3y37NEPwnyZBF94ga2OFLcnC5TuRZCbBv180ZAoCOWr4ZBwkgdDs5GQMmrC9PqSQKZAEhaMueoloZAXmN8Na2JeZCpvZC3juaSa4MSpW6ZBokkewdDzp2XUNBuBZBoqnIeN1kWv5WfGmsiEnZCOxlCBqjE111K4iZCHUkM3LXdKkXY21Xuef2RtYFMiFcJegrIXHZCPBPMa6y";
	Logger logger = LoggerFactory.getLogger(this.getClass());
	List<String> previousList = new ArrayList<String>();
	@Scheduled(fixedDelay=1000 * 60 * 15)//Every 10 minutes
	public void facebookTask(){
		try{
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(facebookPageUrl);
			logger.info("Hitting Url = {}", facebookPageUrl);
			System.out.println("Hitting Url = "+ facebookPageUrl);
			HttpResponse httpResponse = httpClient.execute(httpGet);
			System.out.println("Got Response= "+ httpResponse);
			HttpEntity httpEntity = httpResponse.getEntity();
			System.out.println("Converting to String= "+ httpEntity);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			System.out.println("IOUtils.copy(httpEntity.getContent(), byteArrayOutputStream);");
			IOUtils.copy(httpEntity.getContent(), byteArrayOutputStream);
			String facebookFeed = byteArrayOutputStream.toString();
			//System.out.println("data="+data);
			JSONObject jsonObject = new JSONObject(facebookFeed);
			JSONArray dataArray = jsonObject.getJSONArray("data");
			System.out.println("dataArray="+dataArray.length());
			List<String> currentList = new ArrayList<String>(dataArray.length());
			JSONObject onePost;
			for(int i=0;i<dataArray.length();i++){
				try{
					onePost = dataArray.getJSONObject(i);
					currentList.add(onePost.getString("id"));
				}catch(Exception ex){
					ex.printStackTrace();
				}
			}
			
			int totalItems = 0;
			//Now compare and see if there is new post
			String title = "Facebook Updates";
			if(previousList.isEmpty()){
				//For first time after server restart update the facebook feed
				facebookCache.setFacebookFeed(facebookFeed);
			}else{
				for(int i=0;i<previousList.size();i++){
					if(currentList.size() > i){
						if(previousList.get(0).equals(currentList.get(i))){
							//as soon as same id found break the loop
							break;
						}
						try{
							title = dataArray.getJSONObject(i).getString("message").substring(0, 45);	
						}catch(Exception ex){
							title = "New Photo Added";
							ex.printStackTrace();
						}
						totalItems++;
					}
				}
			}
			previousList = currentList;
			
			System.out.println("Total New items are : "+totalItems);
			if(totalItems > 0 ){
				//If something changed then only update the facebook feed
				facebookCache.setFacebookFeed(facebookFeed);
				NewFacebookNotificationMessage notificationMessage = new NewFacebookNotificationMessage();
				notificationMessage.setNotificationTitle(title);
				notificationMessage.setTotalItem(totalItems);
				
				taskManager.runSendMessageTask(NotificationMessage.NEW_FACEBOOK_MESSAGE, notificationMessage);
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
}
